<script lang="ts" setup>
import type { Column, TableRequest } from '@king-one/antdv'
import { getCompanyList, getTenantList } from '@/apis/tenant'
import { KProTable } from '@king-one/antdv'
import TenantAdd from './components/TenantAdd'

const columns = ref<Column[]>([
  {
    title: '租户名称',
    dataIndex: 'tenantName',
    align: 'center',
    ellipsis: true,
    width: '200px',
  },
  {
    title: '租户描述',
    dataIndex: 'tenantDesc',
    align: 'center',
    ellipsis: true,
    hideInForm: true,
    width: '160px',
  },
  {
    title: '所属企业名称',
    dataIndex: 'companyName',
    align: 'center',
    ellipsis: true,
    valueType: 'select',
    hideInForm: false,
    width: 200,
    request: async () => {
      const res = await getCompanyList()
      return res.data.options
    },
    customRender: ({ text }) => {
      return h('div', null, text)
    },
  },
  {
    title: '企业代码',
    dataIndex: 'creditCode',
    key: 'creditCode',
    align: 'center',
    ellipsis: true,
    hideInForm: true,
    width: '200px',
  },
  {
    title: '状态',
    dataIndex: 'tenantStatus',
    align: 'center',
    key: 'tenantStatus',
    valueType: 'select',
    hideInForm: false,
    valueEnum: {
      ENABLE: {
        text: '正常',
        status: 'Success',
      },
      DISABLE: {
        text: '禁用',
        status: 'Error',
      },
    },
    width: 120,
    customRender: ({ text }) => {
      return h('div', null, text === 'ENABLE' ? '正常' : '禁用')
    },
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    align: 'center',
    ellipsis: true,
    width: '200px',
    valueType: 'dateRange',
    hideInForm: true,
    fieldProps: {
      valueFormat: 'YYYY-MM-DD',
    },
  },
  {
    title: '更新时间',
    dataIndex: 'updateTime',
    align: 'center',
    width: '200px',
    ellipsis: true,
    hideInForm: true,
  },
])

const tableRef = ref()
const tenantAddRef = ref()

function onAdd() {
  tenantAddRef.value.open()
}

const request: TableRequest = async (params) => {
  try {
    const res = await getTenantList({ ...params, companyId: params.companyName })
    console.log(res)

    return {
      data: res.data.list,
      success: true,
      total: res.data.total,
    }
  }
  catch (error) {
    return {
      data: [],
      success: false,
      total: 0,
    }
  }
}
</script>

<template>
  <div class="w-full h-full  rounded-8px p-10px">
    <KProTable
      ref="tableRef"
      :columns="columns"
      :antd-table-props="{
        bordered: true,
      }"
      :request="request"
      :page-size="10"
    >
      <template #toolbar>
        <div class="w-full flex flex-row justify-end">
          <AButton type="primary" ghost @click="onAdd">
            新增
          </AButton>
        </div>
      </template>
    </KProTable>
    <TenantAdd ref="tenantAddRef" @success="() => tableRef.onRefresh()" />
  </div>
</template>
